import os
import shutil
import yaml

'''
    文件操作工具类
'''
class fileUtil:
    __instance = None  # 实例

    def __new__(cls, *args, **kwargs):
        '''
        单实例
        :param args:
        :param kwargs:
        :return:
        '''
        if not cls.__instance:
            cls.__instance = super(fileUtil, cls).__new__(cls, *args)
        return cls.__instance

    def del_files(self, path):
        delList = os.listdir(path)
        for f in delList:
            filePath = os.path.join(path, f)
            if os.path.isfile(filePath):
                os.remove(filePath)
                print(filePath + " 已删除!")
            elif os.path.isdir(filePath):
                shutil.rmtree(filePath, True)
                print("目录: " + filePath + " 已删除!")

    def get_yml_file_path(self, file_name):
        file_path = None
        print(os.name)
        try:
            project_name = ""
            # windows系统下获取工程名
            if os.name == "nt":
                file_dirs = os.path.split(file_name)[0]
                # 处理“D:/Software/WorkSpace/Python/”这种格式的路径
                if file_dirs.find("/") != -1:
                    project_name = file_dirs.split("/")[len(file_dirs.split("/")) - 1]  # 倒数第一个目录

                elif file_dirs.find("\\") != -1:
                    project_name = file_dirs.split("\\")[len(file_dirs.split("/")) - 3]  # 取工程名

            # linux系统下获取工程名
            elif os.name == "posix":
                file_dirs = os.path.split(file_name)[0]

                if file_dirs.find("/") != -1:
                    project_name = file_dirs.split("/")[len(file_dirs.split("/")) - 2]

            # 拼接出yml测试数据文件的绝对路径
            if project_name == 'testcases':
                file_path = file_name.replace(project_name, "testdatas")[:-8] + ".yml"
                suffix = '_smoke'
                if file_path.find(suffix) > 0:
                    file_path = ''
            else:
                file_path = os.path.join(
                    os.path.realpath(os.path.dirname(os.path.dirname(os.path.dirname(file_name)))),
                    project_name, "testdatas",
                    os.path.basename(file_name)[:-8]) + ".yml"

            self.file_path = file_path
        except Exception as e:
            print("yml测试数据文件路径有误！" + str(e))
        return file_path

    def get_test_data_by_name(self, file_name):
        '''
        根据test case的名字自动获取对应的yml格式测试数据
        :param file_name: test case的名字  os.path.abspath( __file__ )
        :return:
        '''
        return self.connect_to(self.get_yml_file_path(file_name)).parsed_data, self.file_path

    def connect_to(self, file_path):
        factory = None
        try:
            factory = self.connection_factory(file_path)
        except ValueError as ve:
            print(ve)
        return factory

    def connection_factory(self, file_path):
        if file_path.endswith("yml"):
            connector = self.YAMLConnector
        else:
            raise ValueError("文件格式错误，Can't connect to {}".format(file_path))
        return connector(file_path)

    class YAMLConnector:
        def __init__(self, file_path):
            with open(file_path, "rb")as f:
                self.data = yaml.load(f)

        @property
        def parsed_data(self):
            return self.data


fileUtils = fileUtil()
